var rosObj = null

var rosUrl = ""

var topic = {
  pose: null,
}

var callBackFun = {
  pose: null,
}

// 心跳状态 1 存在 0 不存在
var poseHeartStatus = 0;

exports.install = function (Vue, options) {
  Vue.prototype.robotPoseRosInit = function (data) {
    console.log("robot pose ros init");
    rosObj = new ROSLIB.Ros();
    monitorsHeart();
    return rosObj;
  }

  Vue.prototype.robotPoseRosConnect = function (data) {
    if (data && data.url) {
      console.log("robot pose ros connect");
      rosObj.connect(data.url);
      rosUrl = data.url
      return true;
    } else {
      return false;
    }
  }

  Vue.prototype.robotPoseRosClose = function (data) {
    console.log("robot pose ros close");
    rosObj.close();
    return true;
  }

  Vue.prototype.robotPoseRosConnectStatus = function (data) {
    console.log("robot pose ros connected");
    return rosObj;
  }

  Vue.prototype.robotPoseRosOnConnection = function (data) {
    rosObj.on("connection", function () {
      console.log("robot pose ros connection");
      rosUnsubscribes()
      rosSubscribes()
    });
    return true;
  }

  Vue.prototype.robotPoseRosOnClose = function (data) {
    rosObj.on("close", function () {
      console.log("robot pose ros close");
    });
    return true;
  }

  Vue.prototype.robotPoseRosOnError = function (data) {
    rosObj.on("error", function (error) {
      console.log("robot pose ros error");
    });
    return true;
  }

  /**				
     *   定位回调				
     *				
     *   @param {*} callBack 回调函数				
     */
  Vue.prototype.poseCallBack = function (callBack) {
    if (callBack instanceof Function) {
      callBackFun.pose = callBack
    } else {
      callBack({
        status: 1001,
        message: "错误：指定类型为Function"
      })
    }
  }
  Vue.prototype.poseUnCallBack = function () {
    callBackFun.pose = null;
  }
};

/**
 *  订阅所有
 *
 */
function rosSubscribes() {
  rosPoseSubscribe();
}

/**
 *  取消订阅所有
 *
 */
function rosUnsubscribes() {
  rosPoseUnsubscribe();
}

/**
 *  定位声明和订阅
 *
 */
function rosPoseSubscribe() {
  topic.pose = new ROSLIB.Topic({
    ros: rosObj,
    name: "/robot_pose",
    messageType: "yidamsg/Yida_pose"
  });
  topic.pose.subscribe(message => {
    poseHeartStatus = 1;
    if (callBackFun.pose) {
      callBackFun.pose(message)
    }
  });
}

/**
 *   定位取消订阅
 *
 */
function rosPoseUnsubscribe() {
  if (topic.pose) {
    topic.pose.unsubscribe();
  }
}


function monitorsHeart() {
  setInterval(() => {
    if (poseHeartStatus == 1) {
      poseHeartStatus = 0;
    } else {
      console.log("ros robot pose heartStatus", poseHeartStatus)
      rosObj.connect(rosUrl);
    }
  }, 3000);
}

